package graph;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2024-05-27
 * Time: 13:17
 */
public class GraphByMatrix {
    public char[] arrayV;
    public int[][] matrix;
    public boolean isDirect;
    public GraphByMatrix(int size,boolean isDirect){
        arrayV =new char[size];
        matrix =  new int[size][size];
        for (int i = 0; i < size; i++) {
            Arrays.fill(matrix[i] ,Constant.MAX);
        }
        this.isDirect = isDirect;
    }
    //初始化
    public void initArrayV(char[] array){
        for (int i = 0; i < array.length; i++) {
            arrayV[i] = array[i];
        }
    }
    //添加边
    public void addEdge(char src , char dest,int weight){
        int sreIndex = getIndexOfV(src);
        int destIndex = getIndexOfV(dest);
            matrix[sreIndex][destIndex] = weight;
        if(! isDirect){
            matrix[destIndex][sreIndex] = weight;
        }


    }
    private int getIndexOfV(char ch){
        for (int i = 0; i < arrayV.length; i++) {
            if(arrayV[i] == ch){
                return i;
            }
        }
        return -1;
    }
    //获取顶点的度
    public int getDevOfV(char ch){
        int count = 0;
        int index = getIndexOfV(ch);
        for (int i = 0; i < matrix[index].length; i++) {
            if(matrix[index][i] != Constant.MAX){
                count++;
            }

        }
        if(isDirect){
            for (int i = 0; i < matrix.length; i++) {
                if(matrix[i][index] != Constant.MAX){
                    count ++;
                }
            }
        }
        return count;
    }
    public void printGraph(){
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                if(matrix[i][j] == Constant.MAX){
                    System.out.print("∞ ");
                }else{
                    System.out.print(matrix[i][j]+" ");
                }

            }
            System.out.println();
        }
    }

    public static void main(String[] args) {

        GraphByMatrix graph = new GraphByMatrix(4,false);
        char[] array = {'A','B','C','D'};
        graph.initArrayV(array);

        graph.addEdge('A','B',1);
        graph.addEdge('A','D',1);
        graph.addEdge('B','A',1);
        graph.addEdge('B','C',1);
        graph.addEdge('C','B',1);
        graph.addEdge('C','D',1);
        graph.addEdge('D','A',1);
        graph.addEdge('D','C',1);
        System.out.println();
        graph.printGraph();
        System.out.println(graph.getDevOfV('A'));
    }

}
